<template>
	<Card :bordered="false" dis-hover>
		<div class="ivu-pt-8 ivu-mb-16">
			<Row type="flex" justify="space-between">
				<Col>
				<DatePicker :editable="false" type="daterange" transfer v-model="timer" placeholder="请选择创建视图时间段"
					style="width: 200px" @on-change="askDataing"></DatePicker>
				<Select v-width="150" clearable class="ivu-ml-16" placeholder="请选择部门" v-model="params.department_id"
					@on-change="askDatas">
					<Option v-for="item in departmentlists" :value="item.value" :key="item.value">{{ item.label }}</Option>
				</Select>
				<Select v-width="150" v-if="params.department_id" clearable class="ivu-ml-16" placeholder="请选择人员"
					v-model="params.member_ids" @on-change="askDataing">
					<Option v-for="item in departmentList" :value="item.value" :key="item.value">{{ item.label }}</Option>
				</Select>
				</Col>
				<Col>
				<Button type="success" v-hasC="{
                            name: 'v1-data-setting-view-create-view',
                            flag: 'v1/data/setting-view/create-view',
                        }" @click="routineview({id:''})">常规视图</Button>
				<Button type="primary" v-hasC="{
                            name: 'v1-data-setting-view-create-view3',
                            flag: 'v1/data/setting-view/create-view',
                        }" class="ivu-ml-16" @click="operationedit({id: ''})">动态视图</Button>
				</Col>
			</Row>
		</div>
		<Table highlight-row :loading="loading" :columns="columns" :data="list" @on-sort-change="sortchange">
			<template slot="type" slot-scope="{ row }">
				<span v-if="+row.type === 0">常规</span>
				<span v-if="+row.type === 1">动态</span>
			</template>
			<template slot="num_patient" slot-scope="{ row }">
				<div class="spin-col" v-if="spinShow1">
					<Spin fix>
						<Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
					</Spin>
				</div>
				<div v-else>{{row.num_patient}}</div>
			</template>
			<template slot="num_times" slot-scope="{ row }">
				<div class="spin-col" v-if="spinShow2">
					<Spin fix>
						<Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
					</Spin>
				</div>
				<div v-else>{{row.num_times}}</div>
			</template>
			<template slot="view_condition" slot-scope="{ row }">
				<Tooltip trigger="hover" placement="right" maxWidth="400">
					<span v-for="(item, index) in row.view_condition" :key="index">
						<Tag v-if="index < 3">{{ item }}</Tag>
					</span>
					<div slot="content">
						<Tag v-for="(item, index) in row.view_condition" :key="index">{{ item }}</Tag>
					</div>
				</Tooltip>
			</template>
			<template slot="view_push" slot-scope="{ row }">
				<Tooltip trigger="hover" placement="right" maxWidth="400">
					<span v-for="(item, index) in row.view_push" :key="index">
						<Tag v-if="index < 3">{{ item }}
						</Tag>
					</span>
					<div slot="content">
						<Tag v-for="(item, index) in row.view_push" :key="index">{{ item }}</Tag>
					</div>
				</Tooltip>
			</template>
			<template slot="operation" slot-scope="{ row }">
				<a v-hasC="{
                            name: 'v1-data-setting-view-normal-detail',
                            flag: 'v1/data/setting-view/normal-detail',
                        }" v-if="+row.type === 0" @click="operationdetailed(row)">详细</a>
				<Divider v-hasC="{
                            name: 'v1-data-setting-view-normal-detail',
                            flag: 'v1/data/setting-view/normal-detail',
                        }" v-if="+row.type === 0" type="vertical"></Divider>
				<a v-hasC="{
                            name: 'v1-data-setting-view-dynamic-detail',
                            flag: 'v1/data/setting-view/dynamic-detail',
                        }" v-if="+row.type === 1" @click="operationdetailed(row)">详细</a>
				<Divider v-hasC="{
                            name: 'v1-data-setting-view-dynamic-detail',
                            flag: 'v1/data/setting-view/dynamic-detail',
                        }" v-if="+row.type === 1" type="vertical"></Divider>
				<a v-hasC="{
                            name: 'v1-data-setting-view-create-view2',
                            flag: 'v1/data/setting-view/create-view',
                        }" v-if="+row.type === 0" @click="operationedit(row)">编辑</a>
				<Divider v-hasC="{
                            name: 'v1-data-setting-view-create-view2',
                            flag: 'v1/data/setting-view/create-view',
                        }" v-if="+row.type === 0" type="vertical"></Divider>
				<a v-hasC="{
                            name: 'v1-data-setting-view-create-view4',
                            flag: 'v1/data/setting-view/create-view',
                        }" v-if="+row.type === 1" @click="operationedit(row)">编辑</a>
				<Divider v-hasC="{
                            name: 'v1-data-setting-view-create-view4',
                            flag: 'v1/data/setting-view/create-view',
                        }" v-if="+row.type === 1" type="vertical"></Divider>
				<a v-hasC="{
                            name: 'v1-data-setting-view-delete-view',
                            flag: 'v1/data/setting-view/delete-view',
                        }" v-if="+row.type === 0" @click="operationdelete(row.id)">删除</a>
				<a v-hasC="{
                            name: 'v1-data-setting-view-delete-view2',
                            flag: 'v1/data/setting-view/delete-view',
                        }" v-if="+row.type === 1" @click="operationdelete(row.id)">删除</a>
			</template>
		</Table>
		<div class="ivu-mt ivu-text-center">
			<Page show-total show-elevator show-sizer :total="total" :current.sync="params.page" :page-size="params.pageSize"
				:page-size-opts="pageOpts" @on-change="formSize" @on-page-size-change="formChangePage" />
		</div>
		<Modal v-model="showCreate" width="580" :mask-closable="false" :closable="false">
			<Form ref="create" :model="modalparams" :rules="ruleValidate">
				<FormItem prop="title">
					<Input v-model="modalparams.title" maxlength="10"
						@on-keyup="modalparams.title=modalparams.title.replace(/\s+|[\r\n]/g,'')" placeholder='请输入视图标题名称'></Input>
				</FormItem>
				<div class="sky-tit">推送到</div>
				<FormItem :rules="{required: true, message: `请选择部门${index+1}`, trigger: 'change'}"
					v-for="(items,index) in modalparams.push_lists" :prop="'push_lists.' + index + '.department_id'"
					:label="`部门${index+1}`" :key="index">	
					<template v-if='items.personList.length>0||items.add||departmentlists.map(e=>e.value).indexOf(items.department_id)>-1'>				
						<Select v-width="118" placeholder="请选择部门" v-model="items.department_id" clearable
							@on-change="statusselect(index, items.department_id)">
							<Option :disabled="disabledstatus.indexOf(item.value)>-1" v-for="item in departmentlists"
								:key="item.value" :value="item.value">{{item.label}}</Option>
						</Select>
						<Select style="width:auto;" :max-tag-count='3' v-model="items.member_ids" class="ivu-ml-8 ivu-inline-block" placeholder="请选择人员" multiple>
							<Option v-for="item in items.personList" :key="item.value" :value="item.value">{{item.label}}
							</Option>
						</Select>
						<Button v-if="modalparams.push_lists.length !== 1" class="ivu-ml-8" type="default"
							@click="handleRemove(index)">删除</Button>
					</template>
					<template v-else>				
						<Select v-width="118" :disabled="true" placeholder="请选择部门" v-model="items.department_name">
							<Option :value="items.department_name">{{items.department_name}}</Option>
						</Select>
						<Select style="width:auto;" :disabled="true" :max-tag-count='3' v-model="items.member_name" class="ivu-ml-8 ivu-inline-block" placeholder="请选择人员" multiple>
							<Option  v-for="item in items.member_name" :key="item" :value="item">{{item}}
							</Option>
						</Select>
					</template>
				</FormItem>
				<FormItem>
					<Button type="dashed" icon="md-add" @click="handleAddItem">添加</Button>
				</FormItem>
			</Form>
			<div slot="footer">
				<Button @click="handleCancel">取消</Button>
				<Button type="primary" @click="handleCreate">确定</Button>
			</div>
		</Modal>
		<jgdata ref="jgdata" @on-closes="askData" />
		<detailed ref="detailed" />
	</Card>
</template>
<script>
	import {
		settingviewdeleteview,
		settingviewcreateview,
		settingviewviewlist,
		settingviewviewcallback,
		settingviewviewcallbacktimes,
		settingviewgetparamslist,
	} from "@/api/hqapi/indexone";
	import { getDepartmentRole } from "@/api/TApi";
	import jgdata from "./data";
	import detailed from "./detailed";
	import jgSearch from "@/components/search";
	export default {
		components: {
			jgSearch, jgdata, detailed
		},
		data() {
			return {
				spinShow1: true,
				spinShow2: true,
				showCreate: false,
				ruleValidate: {
					title: [
						{ required: true, message: '请输入视图标题名称', trigger: 'blur, change' },
					],
				},
				edit: false,
				columns: [
					{
						title: "名称",
						key: 'title',
						width: 200,
						fixed: "left",
					},
					{
						title: "患者数",
						key: 'patient_num',
						width: 100,
					},
					{
						title: "到诊数",
						key: 'patient_arrived_num',
						sortable: "custom",
						width: 100,
					},
					{
						title: "回访人数",
						key: 'num_patient',
						slot: 'num_patient',
						minWidth: 100,
					},
					{
						title: "回访次数",
						key: 'num_times',
						slot: 'num_times',
						minWidth: 100,
					},
					{
						title: "条件",
						slot: 'view_condition',
						minWidth: 350,
					},
					{
						title: "推送部门/人员",
						slot: 'view_push',
						minWidth: 200,
					},
					{
						title: "视图类型",
						key: 'type',
						slot: "type",
						sortable: "custom",
						width: 120,
					},
					{
						title: "创建时间",
						key: 'created_at',
						sortable: "custom",
						width: 130,
					},
					{
						title: "创建人",
						key: 'realname',
						width: 100,
					},
					{
						title: "操作",
						slot: "operation",
						fixed: "right",
						width: 200,
					},
				],
				timer: [],
				loading: false,
				// 请求参数
				params: {
					page: 1,
					pageSize: 10,
					start_time: '',
					end_time: '',
					department_id: '',
					member_ids: '',
					sort_arrived_num: 0,
					sort_type: 0,
					sort_created_at: 0,
				},
				list: [],
				departmentlist: [],
				departmentList:[],
				departmentlists:[],
				total: 0,
				modalparams: {
					id: '',
					type: 0,
					title: '',
					push_lists: [
                        {
							department_id: "",
							department_name:"",
							member_ids: [],
							member_name:[],
                            personList: [],
                        }
                    ]
				},
				pageOpts: [10, 15, 20, 30, 50, 500], // 分页每页数量
				disabledstatus: []				
			};
		},
		mounted() {
			this.initial();
		},
		methods: {
			// 初始化
			initial() {
				this.modalparams = {
					id: '',
					type: 0,
					title: '',
					push_lists: [
                        {
                            department_id: "",
							department_name:"",
							member_ids: [],
							member_name:[],
                            personList: [],
                        }
                    ]
				}
				settingviewgetparamslist().then(res => {
					this.departmentlists = res.department
				})
			
				this.askData();
			},
			// 请求数据
			askData() {
				this.loading = true;
				this.spinShow1 = true;
				this.spinShow2 = true;
				this.params.start_time = this.timer[0]
				this.params.end_time = this.timer[1]
				this.askDatalist1()
				this.askDatalist2()
				this.askDatalist3()
			},
			askDatalist1(){
				settingviewviewlist(this.params).then((res) => {
					this.list = res.list
					this.total = res.total
					this.loading = false;
				});
			},
			askDatalist2(){
				settingviewviewcallback(this.params).then((res) => {
					for (let item of this.list) {
						for (let items of res) {
							if (item.id === items.id){
								item.num_patient = items.num_patient
							}
						}
					}
					this.spinShow1 = false;
				});
			},
			askDatalist3(){
				settingviewviewcallbacktimes(this.params).then((res) => {
					for (let item of this.list) {
						for (let items of res) {
							if (item.id === items.id){
								item.num_times = items.num_times
							}
						}
					}
					this.spinShow2 = false;
				});
			},
			sortchange(e) {
				if (e.key === "patient_arrived_num") {
					if (e.order === "desc") {
						this.params.sort_arrived_num = 2;
					} else if (e.order === "asc") {
						this.params.sort_arrived_num = 1;
					} else {
						this.params.sort_arrived_num = 0;
					}
					this.params.sort_type = 0;
					this.params.sort_created_at = 0;
				} else if (e.key === "created_at") {
					if (e.order === "desc") {
						this.params.sort_created_at = 2;
					} else if (e.order === "asc") {
						this.params.sort_created_at = 1;
					} else {
						this.params.sort_created_at = 0;
					}
					this.params.sort_arrived_num = 0;
					this.params.sort_type = 0;
				} else if (e.key === "type") {
					if (e.order === "desc") {
						this.params.sort_type = 2;
					} else if (e.order === "asc") {
						this.params.sort_type = 1;
					} else {
						this.params.sort_type = 0;
					}
					this.params.sort_arrived_num = 0;
					this.params.sort_created_at = 0;
				}
				this.params.page = 1;
				this.askData();
			},
			askDataing() {
				this.params.page = 1
				this.params.pageSize = 10
				this.params.start_time = this.timer[0]
				this.params.end_time = this.timer[1]
				this.askData()
			},
			askDatas() {
				this.params.page = 1
				this.params.pageSize = 10
				getDepartmentRole({ department_id: this.params.department_id }).then(res => {
					this.departmentList = res
				})
				this.askData()
			},
			/* @函数功能: 分页 */
			formSize(e) {
				this.params.page = e;
				this.askData();
			},
			/* @函数功能: 每页数量 */
			formChangePage(e) {
				this.params.pageSize = e;
				this.askData();
			},
			routineview(row) {
				this.disabledstatus=[]
				this.$refs.create.resetFields();				
				if (row.id) {
					this.modalparams.id = row.id
					this.modalparams.title = row.title
					this.modalparams.push_lists = []
					if (row.view_push_arr.length > 0) {
						for (let index in row.view_push_arr) {
							this.modalparams.push_lists.push({
								department_id: row.view_push_arr[index].department_id,
								member_ids: row.view_push_arr[index].member_ids,
								department_name:row.view_push_arr[index].department_name,
								member_name:row.view_push_arr[index].member_name,
								personList: [],
							})
							this.disabledstatus.push(row.view_push_arr[index].department_id)
							this.departmentfun(index, row.view_push_arr[index].department_id)
						}
					} else {
						this.modalparams.push_lists = [
							{
								department_id: "",
								department_name:"",
								member_ids: [],
								member_name:[],
								personList: []
							}
						]
					}
				}else{
					this.modalparams={
						id: '',
						type: 0,
						title: '',
						push_lists :[
							{
								department_id: "",
								department_name:"",
								member_ids: [],
								member_name:[],
								personList: [],
								add:true
							}
						]
					}
				}
				this.showCreate = true
			},
			handleCreate() {				
				this.$refs.create.validate((valid) => {
					if (valid) {
						let list = []
						for (let item of this.modalparams.push_lists) {
							list.push({ department_id: item.department_id, member_id: item.member_ids })
						}
						let params={
							id:this.modalparams.id,
							type:this.modalparams.type,
							title:this.modalparams.title,
							push_list:JSON.stringify(list)
						}
						settingviewcreateview(params).then(res => {
							if (this.modalparams.id) this.$Message.success('编辑常规视图成功')
							else this.$Message.success('新增常规视图成功')
							this.showCreate = false
							this.askData()
						})
					}
				})
			},
			handleCancel() {
				this.showCreate = false
				this.$refs.create.resetFields();
			},
			operationdetailed(row) {
				if (+row.type === 0) {
					this.$refs.detailed.initial(row)
				} else this.$refs.detailed.initials(row.id)
			},
			operationedit(row) {
				this.$refs.create.resetFields();	
				if (row.id && +row.type === 0) {
					this.routineview(row)
				} else this.$refs.jgdata.initial(row.id)
			},
			operationdelete(id) {
				this.$Modal.confirm({
					title: "删除提示",
					content: "是否确认删除视图，删除后不可恢复，数据切回到默认视图",
					onOk: () => {
						settingviewdeleteview({ id }).then((res) => {
							this.$Message.success("删除成功");
							this.askData();
						});
					},
				});
			},
			handleAddItem() {				
                this.modalparams.push_lists.push(
                    {
                        department_id: "",
						department_name:"",
						member_ids: [],
						member_name:[],
						personList: [],
						add:true
                    }
                )
			},
			departmentfun(index, department_id) {
				if(department_id){
					getDepartmentRole({ department_id }).then(res => {
						this.modalparams.push_lists[index].personList = res
					})
				}else{
					this.modalparams.push_lists[index].personList = []
					this.modalparams.push_lists[index].member_ids = []
				}
                
            },
			statusselect(index, e) {
				this.modalparams.push_lists[index].personList = []
				this.modalparams.push_lists[index].member_ids = []
				this.modalparams.push_lists[index].add=true
                this.disabledstatus[index] = e
                this.departmentfun(index, e)
            },
			handleRemove(index) {
                this.modalparams.push_lists.splice(index, 1)
                this.disabledstatus.splice(index, 1)
            }
		},
	};
</script>
<style>
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
    @keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
    .spin-col{
        height: 25px;
        position: relative;
		background: rgba(0,0,0,0);
    }
	.spin-col .ivu-spin{
		background: rgba(0,0,0,0);
	}
</style>